package cool.taomu.toolkit.service.centre.kademlia.service

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.google.inject.Inject
import cool.taomu.toolkit.service.centre.kademlia.utils.ServiceCentreClientPool
import cool.taomu.toolkit.service.kademlia.entity.FindServiceNodeEntity
import cool.taomu.toolkit.service.kademlia.entity.KPeerNode
import cool.taomu.toolkit.service.kademlia.thrift.ServiceEntity
import cool.taomu.toolkit.utils.ByteBufferUtils
import java.nio.charset.StandardCharsets
import java.util.List
import java.util.function.Function
import org.slf4j.LoggerFactory

/**
 * 远程节点查找
 */
class FindServiceNodeService implements Function<FindServiceNodeEntity, List<KPeerNode>> {
    val static LOG = LoggerFactory.getLogger(FindNodeServiceFunc);

    @Inject
    ServiceCentreClientPool clientPool;

    override apply(FindServiceNodeEntity t) {

        var opl = clientPool.peerClient(t.node, t.localNode, [ client |
            LOG.info("向节点：{}，请求findServiceNode 服务名 ：{}", t.node, t.dto)
            var message = t.dto;
            var dto = new ServiceEntity();
            dto.serviceName = message.serviceName;
            dto.method = message.method;
            dto.params = message.params;
            dto.contentType = message.contentType;
            dto.cookie = message.cookie
            dto.body = message.body;
            var resp = client.findServiceNode(dto, t.excludeIds);
            LOG.info("请求结果 ：{}", resp)
            if (resp.status == 200) {
                var data = ByteBufferUtils.toString(resp.data, StandardCharsets.UTF_8)
                return new Gson().fromJson(data, new TypeToken<List<KPeerNode>>() {
                });
            }
            return null;
        ])
        if (opl.present) {
            return opl.get()
        }
        return #[]
    }

}
